package com.lf125.plus.plugin.LF125PlusPlugin;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.panling.deviceapi.DeviceAPI;
import com.pl.serialport.SerialPort;
import com.znht.iodev2.PowerCtl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class LF125KTagReadThread {

    private String path = "/dev/ttyS1" ;
    private int rate = 9600 ;
    private PowerCtl powerCtl ;
    private DeviceAPI LF125Ctl ;
    private SerialPort mSerial ;
    private InputStream in ;
    private OutputStream out ;
    private Handler handler ;
    private ReadThread readThread ;
    private boolean isRead = false ;

    private static final String TAG = "LF125KKTagReadThread";
    public static final int MSG_RESULT = 1101 ;
    public static  int count = 0;
    public static  int size1,size2,size3,sizeall;
    public static  byte[] buffer1 = new byte[128];
    public static  byte[] buffer2 = new byte[128];
    public static  byte[] buffer3 = new byte[64];
    public static  byte[] bufferall = new byte[320];

    public void setPath(String path) {
        this.path = path ;
    }

    public void setHandler(Handler handler) {
        this.handler = handler ;
    }

    //init thread
    public void init() {
        Log.e("LF134KTag", "init");
        LF125Ctl = DeviceAPI.getInstance();
        panling_power_up();
        //powerCtl = new PowerCtl() ;
        //powerCtl.identity_uhf_power(1);
        //powerCtl.identity_ctl(1);
        //powerCtl.uhf_ctl(1);
        try {
            mSerial = new SerialPort(path,rate,0) ;
            in = mSerial.getInputStream() ;
            out = mSerial.getOutputStream() ;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startRead() {
        isRead = true ;
        if (readThread == null) {
            readThread = new ReadThread() ;
            readThread.start();
        }
    }

    public void stopRead() {
        isRead = false ;
        try {
            if (readThread != null) {
                readThread.interrupt();
                readThread = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (readThread != null) {
                readThread = null;
            }
        }
    }

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (isRead) {
                int size;
                try {
                    byte[] buffer = new byte[256];
                    if (in == null) return;
                    size = in.read(buffer);
                    if (size > 0) {
                        //Log.e("LF125KTag", Tools.Bytes2HexString(buffer, size) + " size = " + size);
                        //这里加个判断，如果一次性读到超过12个字节，就直接进入解析，如果分段几次，就走else流程
                        if(size > 12) {
                            getID(buffer, size);
                        }else {
                            switch(count) {
                                case 0:
                                    System.arraycopy(buffer, 0, buffer1, 0, size);
                                    size1 = size;
                                break;

                                case 1:
                                    System.arraycopy(buffer, 0, buffer2, 0, size);
                                    size2 = size;
                                    break;

                                case 2:
                                    System.arraycopy(buffer, 0, buffer3, 0, size);
                                    size3 = size;
                                    break;
                            }
                            count ++;
                            if(count >=3)
                            {
                                System.arraycopy(buffer1, 0, bufferall, 0, size1);
                                System.arraycopy(buffer2, 0, bufferall, size1, size2);
                                System.arraycopy(buffer3, 0, bufferall, size1 + size2, size3);
                                sizeall = size1 + size2 + size3;
                               // Log.e("hejiang", Tools.Bytes2HexString(bufferall, sizeall) + " sizeall = " + sizeall);
                                getID(bufferall, sizeall);
                                count = 0;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }

    //LF134.2 = 02413245423737423930303438333031313030303030303030303000FF03
    //LF125K = 02373930303838384431466303
    private LFTag getID(byte[] buff, int size) {
        LFTag tag = new LFTag() ;
        long id = 0L ;
        byte[] idBuff = new byte[8];
        byte[] user = new byte[2];
        if (buff[0] != 0x02 || buff[size - 1] != 03 || size < 10) {
            return null ;
        }
        //ID
        System.arraycopy(buff, 3, idBuff, 0, 8);
        //
        System.arraycopy(buff, 1, user, 0, 2);
        String idStr = new String(idBuff) ;
        //将十六进制数据解析为数字类型的
        id = Long.parseLong(idStr, 16) ;
        tag.setId(id);
        String countryStr = new String(user);
        countryStr = "0" + countryStr  ;
        if (handler != null && isRead) {
            Message msg = new Message() ;
            msg.what = MSG_RESULT ;
            Bundle b = new Bundle();
            b.putLong("id", id);
            b.putInt("user", Integer.parseInt(countryStr, 16));
            msg.setData(b);
            handler.sendMessage(msg);
        }
//        Log.e("LF134KTag", "String idStr = " + idStr);
//        Log.e("LF134KTag", "long idStr = " + Long.parseLong(idStr, 16));
//        Log.e("LF134KTag", "long countryStr = " + Long.parseLong(countryStr, 16));
        return tag ;
    }



    //
    public static void reverseOrderArray(byte[] arr) {
        // 把原数组元素倒序遍历
        for(int i = 0; i < arr.length/2; i++) {
            // 把数组中的元素收尾交换
            byte temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
    }


    public void close() {
        if (mSerial != null) {
            mSerial.close();
        }
        //if (powerCtl != null) {
           // powerCtl.identity_uhf_power(0);
//            powerCtl.identity_ctl(0);
//            powerCtl.uhf_ctl(0);
        //}
        panling_power_down();
        }

    private static final String vol33 = "/sys/devices/platform/module_power/rfid_en_3v3";
    private static final String vol5 = "/sys/devices/platform/module_power/rfid_print_5v";
    private static final String power = "/sys/devices/platform/module_power/vdd_io_host_en";
    private static final String rst = "/sys/devices/platform/module_power/rfid_rst_3v3";
    private static final String swch = "/sys/devices/platform/module_power/uart_switch_1v8";
    public void panling_power_up() {

/*
        try {
           // writeUhfFile(rst, "1".getBytes());
           // Thread.sleep(100);
            writeUhfFile(power, "1".getBytes());
            Thread.sleep(20);
            writeUhfFile(vol33, "1".getBytes());
            Thread.sleep(20);
            writeUhfFile(vol5, "1".getBytes());
            Thread.sleep(10);
        }catch(Exception ex){}
 */
        LF125Ctl.LF125Poweron();


    }

    public void panling_power_down() {

/*

        try {
            writeUhfFile(vol5, "0".getBytes());
            Thread.sleep(10);
            writeUhfFile(vol33, "0".getBytes());
            Thread.sleep(10);
            writeUhfFile(power, "0".getBytes());
            Thread.sleep(10);
            //writeUhfFile(rst, "0".getBytes());
            //Thread.sleep(10);
        }catch(Exception ex){}
 */
        LF125Ctl.LF125Powerdown();
    }

/*
    public static void writeUhfFile(String path, byte[] value) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            fos.write(value);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d(TAG,"-----writeUhfFile-----e1=" + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG,"-----writeUhfFile-----e2=" + e.getMessage());
            e.printStackTrace();
        }
    }
 */

}
